package com.db.aggregation;

import com.db.protocol.message.ReportMessage;
import com.db.protocol.message.ReportMessagePerStockAndSide;
import com.db.protocol.tags.OrderSide;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author nulls.narik
 */
public class StockAndSideAggregation extends AbstractAggregation {

    Map<OrderSide, Map<String, ReportMessagePerStockAndSide>> map;

    public StockAndSideAggregation() {
        map = new HashMap<OrderSide, Map<String, ReportMessagePerStockAndSide>>();
        map.put(OrderSide.BUY, new HashMap<String, ReportMessagePerStockAndSide>());
        map.put(OrderSide.SELL, new HashMap<String, ReportMessagePerStockAndSide>());
    }

    @Override
    protected void clear() {
        map.get(OrderSide.BUY).clear();
        map.get(OrderSide.SELL).clear();
    }

    @Override
    protected void add(ReportMessage message) {
        Map<String, ReportMessagePerStockAndSide> mapOrderSide  = map.get(message.getOrderSide());
        if (mapOrderSide.containsKey(message.getStockName())) {
            mapOrderSide.get(message.getStockName()).add(message);
        } else {
            mapOrderSide.put(message.getStockName(), new ReportMessagePerStockAndSide(message));
        }
    }

    @Override
    protected List<ReportMessage> getList() {
        List<ReportMessage> list = new LinkedList<ReportMessage>(map.get(OrderSide.SELL).values());
        list.addAll(map.get(OrderSide.BUY).values());
        return list;
    }
}
